from PyQt5.QtWidgets import QTabWidget
from PyQt5.QtCore import pyqtSignal, QBuffer, QIODevice, Qt,QPointF
from PyQt5.QtGui import QPixmap
from image_viewer import ImageViewer
import os
import tempfile

class TabManager(QTabWidget):
    rect_selected = pyqtSignal(dict)  # 添加信号用于传递矩形参数
    del_selected = pyqtSignal()  
    color_selected = pyqtSignal(str,tuple)

    def __init__(self):
        super().__init__()
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.close_tab)
        # 绑定标签切换事件（currentChanged信号）
        self.currentChanged.connect(self.on_tab_changed)
        # 存储当前活动的viewer引用
        self.current_viewer = None

    def open_img(self, folder_path):
        viewer = ImageViewer(folder_path)
        index = self.addTab(viewer, folder_path.replace("\\","/").split("/")[-1])
        self.setCurrentIndex(index)
        
    def on_rect_selected(self, rect_params):
        # 传递矩形参数信号
        self.rect_selected.emit(rect_params)

    def on_del_selected(self):
        # 传递矩形参数信号
        self.del_selected.emit()    

    def on_color_selected(self,color,pos):
        pos = pos.toPoint()
        self.color_selected.emit(color,(pos.x(),pos.y()))

    def close_tab(self, index):
        widget = self.widget(index)
        if widget:
            widget.deleteLater()
        self.removeTab(index)
        
    def open_cropped_img(self, cropped_pixmap):
        """在新标签页中打开裁剪后的图像"""
        # 将裁剪后的图像保存到临时缓冲区
        buffer = QBuffer()
        buffer.open(QIODevice.WriteOnly)
        cropped_pixmap.save(buffer, "PNG")
        
        # 将缓冲区数据转换回QPixmap
        temp_pixmap = QPixmap()
        temp_pixmap.loadFromData(buffer.data(), "PNG")
        
        # 创建临时文件路径
        temp_path = os.path.join(tempfile.gettempdir(), "cropped_image.png")
        
        # 创建一个新的ImageViewer实例
        viewer = ImageViewer(temp_path)
        
        # 替换viewer中的图像
        viewer.scene.clear()
        item = viewer.scene.addPixmap(temp_pixmap)
        viewer.fitInView(item, Qt.KeepAspectRatio)
        viewer.original_size = temp_pixmap.size()
        viewer.pixmap = temp_pixmap  # 设置pixmap引用以便保存
        
        # 添加到标签页
        index = self.addTab(viewer, "crop")
        self.setCurrentIndex(index)

    def on_tab_changed(self, index):
        # """标签页切换时的响应函数"""
        # 先移除旧标签页的事件绑定
        if self.current_viewer is not None:
            self.del_selected.emit()    
            try:
                self.current_viewer.rect_selected.disconnect(self.on_rect_selected)
                self.current_viewer.del_selected.disconnect(self.on_del_selected)
                self.current_viewer.color_selected.disconnect(self.on_color_selected)
            except TypeError:
                # 如果信号未连接，忽略错误
                pass
        
        # 获取新标签页并绑定事件
        if index >= 0 and index < self.count():
            self.current_viewer = self.widget(index)
            if isinstance(self.current_viewer, ImageViewer):
                self.current_viewer.rect_selected.connect(self.on_rect_selected)
                self.current_viewer.del_selected.connect(self.on_del_selected)
                self.current_viewer.color_selected.connect(self.on_color_selected)
                # 发送当前选中的矩形参数
                rect_param = self.current_viewer.getRectParam()
                if rect_param:
                    self.rect_selected.emit(rect_param)
        else:
            self.current_viewer = None
        

   
        
